<?php

namespace App\Http\Controllers\Admin;

use App\Helpers\ResponseData;
use App\Http\Controllers\Controller;
use App\Http\Requests\LoginRequest;
use App\Models\Admin;
use Illuminate\Support\Facades\Hash;
use Modules\Manager\Entities\Manager;

class LoginController extends Controller
{
    use ResponseData;
    public function login(LoginRequest $request){
        $user = Admin::query()->where('phone', $request->phone)->first();
        if (! $user || ! Hash::check($request->password, $user->password)) {
            return $this->failed('账号或者密码错误',201);
        }
        $data['message'] = '登录成功';
        $data['token'] = $user->createToken($request->phone)->plainTextToken;
        return $this->success($data,200);
    }
    public function checkpwd(LoginRequest $request){
        $user = Admin::query()->where('phone', $request->phone)->first();
        $manager = Manager::query()->where('phone', $request->phone)->first();
        if($manager){
            if($manager->next_change_time < now()){
                return $this->failed('请前往小程序端修改密码后再试',201);
            }
            if (! $manager || ! Hash::check($request->password, $manager->password)) {
                return $this->failed('密码错误',201);
            }
            return $this->success($manager);
        }else{
            if($user->post_id == 2 && $user->next_change_time < now()){
                return $this->failed('请前往小程序端修改密码后再试',201);
            }
            if (! $user || ! Hash::check($request->password, $user->password)) {
                return $this->failed('密码错误',201);
            }
            return $this->success($user);
        }
    }
}
